package cn.xerllent.common.service.impl;

import java.util.HashMap;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;

import cn.xerllent.common.service.AliyunSmsService;

/**
 */
@Service
public class AliyunSmsServiceImpl implements AliyunSmsService {

    @Value("${sms.accessKeyId}")
    private String accessKeyId;

    @Value("${sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${sms.signName}")
    private String signName;

    @Value("${sms.templateCode}")
    private String templateCode;

    private Client client;

    private final Object lock = new Object();

	@Override
	public Client getAliyunSmsClient() throws Exception {
    	synchronized (lock) {
    		if(client==null) {
    	        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
    	                // 必填，您的 AccessKey ID
    	                .setAccessKeyId(accessKeyId)
    	                // 必填，您的 AccessKey Secret
    	                .setAccessKeySecret(accessKeySecret);
    	        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
    	        config.endpoint = "dysmsapi.aliyuncs.com";
    	        client = new com.aliyun.dysmsapi20170525.Client(config);
    		}
		}
    	return client;
	}

	/**
	 * 发送验证码短信
	 * */
	@Override
	public void sendVerifySms(String mobile, String code) throws Exception {
		Client client = getAliyunSmsClient();
		SendSmsRequest sendSmsRequest = new SendSmsRequest();
		// 手机号  验证码  签名 模板ID
		sendSmsRequest.setPhoneNumbers(mobile);
		sendSmsRequest.setSignName(signName);
		sendSmsRequest.setTemplateCode(templateCode);
		HashMap<String, Object> message = new HashMap<>();
		message.put("code", code);
		sendSmsRequest.setTemplateParam(JSON.toJSONString(message));
		SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
		if(!"OK".equals(sendSmsResponse.body.getCode())) {
			throw new Exception(sendSmsResponse.getBody().getMessage());
		}

	}




}
